package org.esiee.mobiliteam;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class RATPHandler extends Activity {

	protected ArrayAdapter<CharSequence> mAdapter;
	protected int mPos;
	protected String mSelection, url, start = null, end = null;
	protected String url0 = null;//"http://www.ratp.fr/horaires/fr/ratp/bus/prochains_passages/PP/B212/212_97_119/A";
	protected String url1 = null;//"http://www.ratp.fr/horaires/fr/ratp/bus/prochains_passages/PP/B212/212_97_119/R";
	protected WebView wv = null;
	protected Handler mHandler = null;
	private ProgressDialog mProgressDialog = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle param = this.getIntent().getExtras();
		this.url0 = (String) param.getString("url0");
		this.url1 = (String) param.getString("url1");
		this.start = (String) param.getString("start");
		this.end = (String) param.getString("end");
		
		setContentView(R.layout.transport);
		url = url0;

		mProgressDialog = ProgressDialog.show(this,getString(R.string.loading),"Info loading",true);
		
		wv = (WebView) findViewById(R.id.ratp_webview);
		wv.setBackgroundColor(Color.parseColor("#000000"));
		this.mHandler = new Handler();
		this.mHandler.postDelayed(m_Runnable,60000*5);
		

		Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
		this.mAdapter = ArrayAdapter.createFromResource(this, R.array.StationBus212,
				android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(this.mAdapter);


		OnItemSelectedListener spinnerListener = new myOnItemSelectedListener(this,this.mAdapter);
		spinner.setOnItemSelectedListener(spinnerListener);


	}//onCreate

	private final Runnable m_Runnable = new Runnable()
	{
		public void run(){
//			Toast.makeText(TransportActivity.this,"in runnable",Toast.LENGTH_SHORT).show();
			wv.loadDataWithBaseURL("", getRatp(url), "text/html", "utf-8", "");
		}

	};//runnable


	public String getRatp(String url){
		try{
			if(!mProgressDialog.isShowing())
				mProgressDialog = ProgressDialog.show(this,getString(R.string.loading),"Info loading",true);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		int start = 0, end = 0;
		StringBuilder sb = new StringBuilder();
		String ratp = getIpFrom(url);
		String startDelim = this.start;//"<div class=\"line_details\">";
		String endDelim = this.end; //"</fieldset>";
		try{
			start = ratp.indexOf(startDelim) - startDelim.length();
			end = ratp.indexOf(endDelim);
			ratp = ratp.substring(start + startDelim.length(), end).replaceAll("(/horaires/.* )", "http://www.ratp.fr$1");
			ratp = ratp.replaceAll("<tr class=\"overall_header\">", "<tr style=\"background-color:#1BA997;"+
					"color:#FFFFFF;" +
					"font-size:20px;" +
					"font-weight:bold;" +
					"color: #FFF;\" >");
			ratp = ratp.replaceAll("<th", "<th style=\"background-color: #61CCBE; font-size:11px;\" ");
			ratp = ratp.replaceAll("<tr class=\"even\"", "<tr style=\"background-color: #EAEAEA;\"");
			ratp = ratp.replaceAll("<table>", "<table style=\"border-style:solid; border-width: 1px; font-size:11px;\">");
			sb.append("<html lang='fr' xml:lang='fr' dir='ltr' xmlns=\"http://www.w3.org/1999/xhtml\" >");
			sb.append("<head /><body style=\"background-color: black;\">");
			sb.append("<fieldset style=\"background-color: white;\">");
			sb.append(ratp);
			sb.append("</body></html>");
		}
		catch(Exception e){
			e.printStackTrace();
			sb.append("<fieldset class=\"nus\" style=\"background-color: white;\">");
			sb.append("<p>"+ getString(R.string.no_info) + "</p><br />");
			sb.append("</fieldset>");
		}
		mProgressDialog.dismiss();
		return sb.toString();
	}

	static String getIpFrom(String adresse) { 
		String toreturn = null;
		try { 
			//		creation d'un objet URL 
			URL url = new URL(adresse); 
			//		on etablie une connection a cette url 
			URLConnection uc = url.openConnection(); 
			//		on y cree un flux de lecture 
			Reader in = new InputStreamReader(uc.getInputStream(), "UTF-8");
			//		on lit le premier bit 
			int c = in.read(); 
			//		on cree un StringBuilder pour par la suite y ajouter tout les bit lus 
			StringBuilder build = new StringBuilder(); 
			//		tant que c n'est pas egale au bit indiquant la fin d'un flux... 
			while (c != -1) { 
				build.append((char) c); 
				//		...on l'ajoute dasn le StringBuilder... 
				c = in.read(); 
				//		...on lit le suivant 
			} 
			//		on retourne le code de la page 
			toreturn = build.toString(); 

		} catch (MalformedURLException e) { 

			e.printStackTrace(); 
		} catch (IOException e) { 

			e.printStackTrace(); 
		}
		return toreturn;
	} 

	public class myOnItemSelectedListener implements OnItemSelectedListener {


		ArrayAdapter<CharSequence> mLocalAdapter;
		Activity mLocalContext;

		/**
		 *  Constructor
		 *  @param c - The activity that displays the Spinner.
		 *  @param ad - The Adapter view that
		 *    controls the Spinner.
		 *  Instantiate a new listener object.
		 */
		public myOnItemSelectedListener(Activity c, ArrayAdapter<CharSequence> ad) {

			this.mLocalContext = c;

		}

		public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {

			RATPHandler.this.mPos = pos;
			//TransportActivity.this.mSelection = parent.getItemAtPosition(pos).toString();
			if(pos == 0) url = url0;
			else if(pos == 1) url = url1;

			wv.loadDataWithBaseURL("", getRatp(url), "text/html", "utf-8", "");
		}

		public void onNothingSelected(AdapterView<?> parent) {

			//
		}
	}
}